package com.woniuxy.charin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.charin.mapper.StationMapper;
import com.woniuxy.charin.model.entity.ChargingPile;
import com.woniuxy.charin.model.entity.Station;
import com.woniuxy.charin.model.vo.PageResponse;
import com.woniuxy.charin.service.ChargingPileService;
import com.woniuxy.charin.service.StationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 服务接口实现
 *
 * @author
 * @description
 * @since 2024-12-23 20:40:30
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class StationServiceImpl
        extends ServiceImpl<StationMapper, Station>
        implements StationService {
    @Autowired
    private StationMapper stationMapper;
    @Autowired
    private ChargingPileService chargingPileService;

    public PageResponse<Station> getStationList(
            String stationName, String status, String address, int page, int size) {
        log.info("getStationList: " +
                        "stationName={}, status={}, address={}, page={}, size={}",
                stationName, status, address, page, size);
        Page<Station> stationPage = new Page<>(page, size);
        // 使用 LambdaQueryWrapper 拼装查询条件
        LambdaQueryWrapper<Station> wrapper = new LambdaQueryWrapper<>();
        // 如果 StationName 不为空，就加上模糊搜索
        if (stationName != null && !stationName.trim().isEmpty()) {
            wrapper.like(Station::getStationName, stationName.trim());
        }
        // 如果 status 不为 null，就加上 status 的条件
        if (status != null) {
            wrapper.eq(Station::getStatus, status);
        }
        // 如果 address 不为空，就加上模糊搜索
        if (address != null && !address.trim().isEmpty()) {
            wrapper.like(Station::getAddress, address.trim());
        }
        // 使用分页查询
        stationPage = stationMapper.selectPage(stationPage, wrapper);
        // 返回查询到的记录
        return new PageResponse<>(stationPage.getTotal(), stationPage.getRecords());
    }

    public void addStation(Station station) {
        log.info("addStation: station={}", station);
        station.setId(null); // 确保 id 为空，由数据库自动生成
        stationMapper.insert(station);
    }

    public void updateStation(Station station) {
        log.info("updateStation: station={}", station);
        stationMapper.updateById(station);
    }

    @Override
    public void offlineStation(int id) {
        log.info("offlineStation: id={}", id);
        Station station = stationMapper.selectById(id);
        station.setStatus("已下线");
        stationMapper.updateById(station);
    }

    @Override
    public void onlineStation(int id) {
        log.info("onlineStation: id={}", id);
        Station station = stationMapper.selectById(id);
        station.setStatus("正常");
        stationMapper.updateById(station);
    }

    public void deleteStation(int id) {
        log.info("deleteStation: id={}", id);
        stationMapper.deleteById(id);
    }

    @Transactional
    @Override
    public List<ChargingPile> createStationWithChargingPiles(Station station, List<ChargingPile> chargingPiles) {
        // 1. 创建站点
        this.save(station);

        // 2. 设置充电桩的站点 ID 并批量保存
        chargingPiles.forEach(pile -> pile.setStationId(station.getId()));
        chargingPileService.saveBatch(chargingPiles);

        return chargingPiles;
    }

    @Transactional
    @Override
    public List<ChargingPile> updateStationWithChargingPiles(Station station, List<ChargingPile> chargingPiles) {
        if (station == null) {
            throw new IllegalArgumentException("Station 参数不能为空");
        }
        if (station.getId() == null) {
            throw new IllegalArgumentException("Station ID 不能为空");
        }

        System.out.println("Updating station: " + station);

        // 更新站点信息
        boolean stationUpdated = this.updateById(station);
        if (!stationUpdated) {
            throw new RuntimeException("更新站点信息失败: " + station.getId());
        }

        // 获取现有充电桩列表
        List<ChargingPile> existingPiles = chargingPileService.listByStationId(station.getId());

        // 删除不存在的充电桩
        List<Long> newPileIds = chargingPiles.stream()
                .map(ChargingPile::getId)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

        existingPiles.stream()
                .filter(pile -> !newPileIds.contains(pile.getId()))
                .forEach(pile -> {
                    boolean removed = chargingPileService.removeById(pile.getId());
                    if (!removed) {
                        throw new RuntimeException("删除充电桩失败: " + pile.getId());
                    }
                });

        // 更新或新增充电桩
        for (ChargingPile pile : chargingPiles) {
            if (pile.getStationId() == null) {
                pile.setStationId(station.getId());
            }

            if (pile.getId() != null) {
                if (!chargingPileService.updateById(pile)) {
                    throw new RuntimeException("更新充电桩失败: " + pile.getId());
                }
            } else {
                boolean pileSaved = chargingPileService.save(pile);
                if (!pileSaved) {
                    throw new RuntimeException("新增充电桩失败");
                }
            }
        }

        return chargingPiles;
    }

}